package yc.gg.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import yc.gg.constants.JwtConstants;

import java.security.Key;
import java.util.Date;

/**
 * * User: Fuyue
 * * Date: 2025/3/12
 * * Description:
 * *
 */
public class JwtUtils {
    private static final long EXPIRATION = 15 * 24 * 60 * 60 * 1000;
    // 生成满足 HS256 安全要求的密钥
    private static final String SECRET_KEY_STRING = JwtConstants.HSKEY;
    private static final Key SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY_STRING.getBytes());

    public static String generateToken(String openid) {
        return Jwts.builder()
                .setSubject(openid)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    public static boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }

    public static String getUserIdFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }
}